package cn.stylefeng.guns.sys.modular.system.service.impl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.core.properties.TcConfig;
import cn.stylefeng.guns.sys.modular.system.entity.ItemUnit;
import cn.stylefeng.guns.sys.modular.system.mapper.ItemUnitMapper;
import cn.stylefeng.guns.sys.modular.system.model.params.ItemUnitParam;
import cn.stylefeng.guns.sys.modular.system.model.result.ItemUnitResult;
import cn.stylefeng.guns.sys.modular.system.service.ItemUnitService;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.io.Serializable;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author jiangge
 * @since 2020-09-17
 */
@Service
public class ItemUnitServiceImpl extends ServiceImpl<ItemUnitMapper, ItemUnit> implements ItemUnitService {
    private Logger logger = LoggerFactory.getLogger(ItemUnitServiceImpl.class);
    private RestTemplate restTemplate = new RestTemplate();

    @Autowired
    private TcConfig tcConfig;

    @Override
    public void add(ItemUnitParam param) {
        ItemUnit entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(ItemUnitParam param) {
        this.removeById(getKey(param));
    }

    @Override
    public void update(ItemUnitParam param) {
        ItemUnit oldEntity = getOldEntity(param);
        ItemUnit newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public ItemUnitResult findBySpec(ItemUnitParam param) {
        return null;
    }

    @Override
    public List<ItemUnitResult> findListBySpec(ItemUnitParam param) {
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(ItemUnitParam param) {
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public void initItemUnitData() {
        String url = "http://btyjt.c3.fxscm.net/cldpoint/getItemUnit.do?ent=ENT7617&username="+tcConfig.getUsername()+"&password="+tcConfig.getPassword();
        String content = restTemplate.getForObject(url, String.class);
        JSONObject resultObject = JSON.parseObject(content);
        JSONArray jsonArray = resultObject.getJSONArray("data");

        //数据转换
        List<ItemUnit> itemTypeList = JSON.parseArray(resultObject.getString("data"), ItemUnit.class);

        if (!CollectionUtils.isEmpty(itemTypeList)) {
            //重新保存之前先把之前所有的删除
            this.baseMapper.deleteAll();
            for (ItemUnit itemUnit : itemTypeList) {
                this.saveOrUpdate(itemUnit);
            }
            logger.info("品项单位数据入库结束：{}条数据", itemTypeList.size());
        }


//        JSONObject jsonObject;
//        List<ItemUnitParam> list = Lists.newLinkedList();
//        logger.info("品项单位数据入库开始：{}条数据", list.size());
//        if (jsonArray != null) {
//            for (int i = 0; i < jsonArray.size(); i++) {
//                ItemUnitParam itemUnitParam = new ItemUnitParam();
//                //把所有 ItemSmallClassName 为 酱料 的添加到list中
//                jsonObject = jsonArray.getJSONObject(i);
//
//                itemUnitParam.setId(jsonObject.getOrDefault("id", "").toString());
//                itemUnitParam.setCode(jsonObject.getOrDefault("code", "").toString());
//                itemUnitParam.setName(jsonObject.getOrDefault("name", "").toString());
//                if(jsonObject.getOrDefault("enableFlag", "").toString().equals("")){
//                    itemUnitParam.setEnableFlag(null);
//                }else {
//                    itemUnitParam.setEnableFlag(Integer.valueOf(jsonObject.getOrDefault("enableFlag", "").toString()));
//                }
//                Date modifyDate = DateUtil.getTimeToDate(jsonObject.getOrDefault("modifyDate", "").toString());
//                itemUnitParam.setModifyDate(modifyDate);
//                itemUnitParam.setParentId(jsonObject.getOrDefault("parentid", "").toString());
//                list.add(itemUnitParam);
//            }
//        }
//
//        //如果有数据则清空店铺表再插入，以免之前的数据也丢失了
//        if(list.size()>0){
//            deleteAll();
//        }
//
//        //插入数据
//        for (ItemUnitParam itemUnitParam : list) {
//            add(itemUnitParam);
//        }
//
//        logger.info("品项单位数据入库结束：{}条数据", list.size());
    }

    private void deleteAll() {
        this.baseMapper.deleteAll();
    }

    private Serializable getKey(ItemUnitParam param) {
        return param.getItemUnitId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private ItemUnit getOldEntity(ItemUnitParam param) {
        return this.getById(getKey(param));
    }

    private ItemUnit getEntity(ItemUnitParam param) {
        ItemUnit entity = new ItemUnit();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

}
